﻿using System;
using Sencha.Serialization.Contracts;
using System.ComponentModel;
using System.Globalization;

namespace Sencha.Serialization.Serializers
{
	public sealed class ConvertibleSerializer<ItemT> : TypeSerializer<ItemT>
	{
		private Type m_convertibleType;

		public ConvertibleSerializer(TypeDescription convertibleType)
		{
			if (convertibleType == null)
				throw new ArgumentNullException("convertibleType");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			if (!convertibleType.IsConvertible)
				throw new Exceptions.TypeContractViolation(this.GetType(), convertibleType, "be convertible");

			this.TypeDescription = convertibleType;

			m_convertibleType = convertibleType.GetClrType();
		}

		public override ItemT Deserialize(IJsonReader reader)
		{
			if (reader == null)
				throw new ArgumentNullException("reader");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			var value = reader.Value.AsType<ItemT>();
			return value;
		}
		public override void Serialize(IJsonWriter writer, ItemT value)
		{
			if (writer == null)
				throw new ArgumentNullException("writer");
			System.Diagnostics.Contracts.Contract.EndContractBlock();

			var valueString = TypeConvert.Convert<ItemT, string>(value, writer.Context.Format);
			if (valueString == null)
				writer.Write(JsonToken.Null);
			else
				writer.Write(valueString);
		}

		public override string ToString()
		{
			return string.Format("convertible({0})", m_convertibleType.Name);
		}
	}
}
